<template>
  <l-popup :="fv.rootProps">
    <Button :class="[ns.e('content')]" type="info">
      <view :class="[ns.e('header')]">
        <view :class="[ns.e('title')]">
          <slot name="title">{{ title }}</slot>
        </view>
        <view :class="[ns.e('close')]" v-if="showClose" @click="closePopup()">
          <slot name="close">
            <image :src="localFile.getImage('public/close')" mode="widthFix"></image>
          </slot>
        </view>
      </view>
      <view :class="[ns.e('body')]">
        <slot></slot>
      </view>
      <view :class="[ns.e('footer')]">
        <slot name="footer">
          <Button v-for="item, i in btns" :="item.props" @click="handle({ row: item, index: i })"
            :loading="item.props?.loading || state.loading[i]?.value">
            <Font :text="item.text" />
          </Button>
        </slot>
      </view>
    </Button>
  </l-popup>
</template>

<script lang="ts" setup>
import { useNamespace } from '@/utils'
import Popup from '.'
import { computed, reactive, useAttrs } from 'vue'
import Button from '@/components/button/index.vue'
import Font from '@/components/font/index.vue'
import localFile from '@/utils/local-file'
import { CatchError } from '@/utils/catch-error'

defineOptions({
  name: Popup.name
})
const props = defineProps(Popup.props)
const emits = defineEmits(Popup.emits)
const attrs = useAttrs() as Omit<Popup.Props, keyof typeof Popup.props>
const ns = useNamespace(Popup.name)
const state = reactive({
  loading: Array<{ value: boolean } | undefined>()
})
const ce = Array<CatchError | undefined>()
const fv = computed(() => {
  const { position = 'center' } = attrs
  const close = props.btns.some((_, i) => state.loading[i]?.value) && !props.loadingClose
  const rootProps: Popup.Props = {
    ...attrs,
    class: [ns.b, ns.b + '--' + position],
    modelValue: props.modelValue,
    position,
    "onUpdate:modelValue": closePopup,
  }
  return {
    rootProps, close
  }
})

function closePopup() {
  if (fv.value.close) return
  emits('update:modelValue', false)
}
function handle(
  { row, index }: { row: (Popup.Props['btns'] & {})[number], index: number }
) {
  if (row.openLoading ?? true) {
    return new Promise((resolve, reject) => {
      if (!ce[index]) {
        state.loading[index] = { value: false }
        ce[index] = new CatchError({ loading: state.loading[index] })
      }
      ce[index].run = () => row.handle?.(closePopup)
      ce[index].success = () => {
        closePopup()
        resolve(true)
      }
      ce[index].fail = reject
    })
  }
  return row.handle?.(closePopup)
}
</script>